package utils

import (
	"time"
)

const TimeFormat = "2006-01-02 15:04:05"

func NowDateUnix() int64 {
	currentTime := time.Now()
	return time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location()).Unix()
}

func NowUnix() int64 {
	return time.Now().Unix()
}

func UnixToDateTime(now int64) string {
	tm := time.Unix(now, 0)
	return tm.Format(TimeFormat)
}

func NowDateTime() string {
	currentTime := time.Now()
	return currentTime.Format(TimeFormat)
}

func NowDate(format string) string {
	if format == "" {
		format = "2006-01-02"
	}
	return time.Now().Format(format)
}

func DateToUnix(t string) int64 {
	currentTime := time.Now()
	if t == "" {
		return NowDateUnix()
	}
	n, _ := time.Parse("2006-01-02", t)

	return time.Date(n.Year(), n.Month(), n.Day(), 0, 0, 0, 0, currentTime.Location()).Unix()
}

func GetForeDate(dt string) string {
	if dt != "" {
		return dt
	}
	nTime := time.Now()
	yesTime := nTime.AddDate(0, 0, -1)
	return yesTime.Format("20060102")
}

// 获取某一天的0点时间
func GetZeroTime(d time.Time) time.Time {
	return time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
}

// 获取传入的时间所在月份的第一天，即某月第一天的0点。如传入time.Now(), 返回当前月份的第一天0点时间。
func GetFirstDateOfMonth(d time.Time) time.Time {
	d = d.AddDate(0, 0, -d.Day()+1)
	return GetZeroTime(d)
}

// 获取传入的时间所在月份的最后一天，即某月最后一天的0点。如传入time.Now(), 返回当前月份的最后一天0点时间。
func GetLastDateOfMonth(d time.Time) time.Time {
	return GetFirstDateOfMonth(d).AddDate(0, 1, -1)
}

var timeTemplates = []string{
	"2006-01-02 15:04:05", //常规类型
	"2006-01-02",
	"2006-01",
	"15:04:05",
}

func StringToTime(str string, index int) time.Time {
	t, err := time.ParseInLocation(timeTemplates[index], str, time.Local)
	if nil == err && !t.IsZero() {
		return t
	}
	return time.Time{}
}
